/**
 * promise
 * @returns
 */
function myPromise(options) {
	//1.创建promise,封装异步任务
	let promise = new Promise(function (resolve, reject) {
		// 2. 封装ajax异步任务
		const xhr = new window.XMLHttpRequest()
		let method = options.method.toUpperCase()
		if (method == 'GET') {
			let params = changeObjParme(options.data)
			xhr.open(method, options.url + '?' + params)
			xhr.send()
		} else if (method == 'POST') {
			xhr.open(method, options.url)
			xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
			let params = changeObjParme(options.data)
			xhr.send(params)
		}

		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					let data = JSON.parse(xhr.responseText)
					resolve(data) //resolve成功状态
				} else {
					reject('请求出错 ' + xhr.status) //reject失败状态
				}
			}
		}
	})
	return promise
}

/**
 * 对象转字符串
 * @param {*} obj 
 * @returns 
 */
function changeObjParme(obj) {
	let arr = [] //[username='admin', password=123]
	for (let key in obj) {
		let params = `${key}=${obj[key]}`
		arr.push(params)
	}
	let line = arr.join('&') //username='admin'&password=123

	return line
}

let product
// function onDetail(id) {
// 	location.href = '../pages/detail.html?id' + id
// 	loadProuctDetail()
// }
/*
	 商品详情
*/
function getProductId() {
	let url = location.href
	// console.log(location.search)
	url = url.substring(url.indexOf('?') + 1)
	let arr = url.split('=')
	let id = arr[1]
	return id
}

/*
	根据ID查询商品详情接口
*/

function loadProuctDetail() {
	let id = getProductId()
	 axios({
		method: 'get',
		url: 'http://api.yuguoxy.com/api/shop/find',
		params: {
			id,

		},
	}).then(response => {
		let data = response.data
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			product = resultInfo
			showProductDetail(product)
		} else {
			alert('失败')
		}
	})
}

/*
	动态渲染
*/
function showProductDetail(product) {
	let liStr = product.list
		.map(item => {
			return `<li><img src="${item}" alt=""></li>`
		})
		.join('')

	let detailStr =
		`<div class="contain" id="glass1">
					        <!-- 左边区域 -->
                                  <div class="wraper-l">
								  <button class="add-cart" onclick="onAddCart()">加入购物车</button>
								  <button class="look-cart" onclick="onLookCart()">查看购物车</button>
                                     <div class="show-box">
									    <img src="${product.picture}" alt="商品">
                                        <div class="mask"></div>
                                     </div>
                                     <ul>` + liStr + `<li class="active"></li></ul>
                           
						          </div>

							<!-- 右边区域 -->
							<div class="wraper-r">
							     <img class="bigImg" src="${product.picture}" alt="商品">
							</div>
					 </div>
			
					<div class="detail-r">
							<div class="title">
								<h2>${product.product}</h2>
								<p class="priceago">￥${product.price * 1.4}<p>
								<p class="pricenow">￥${product.price}</p>
								
							</div>
					</div>`

	const detailWrapper = document.querySelector('.detail-wrapper')
	detailWrapper.innerHTML = detailStr

	let glass = new Glass('#glass1')
	glass.onGlass()
	glass.onShowHide()
	glass.onTab()
}

/*
	放大镜
*/

class Glass {
	constructor(id) {
		this.rootEle = document.querySelector(id)
		//显示盒子
		this.showBox = this.rootEle.querySelector('.show-box')
		//遮罩层
		this.mask = this.rootEle.querySelector('.show-box>.mask')
		//放大镜区域
		this.glassBox = this.rootEle.querySelector('.wraper-r')
		//背景图片
		this.bigPic = this.rootEle.querySelector('.wraper-r>img')
		//所有选项卡
		this.uls = this.rootEle.querySelectorAll('.wraper-l li')
		this.showImg = this.rootEle.querySelector('.show-box>img')
	}
	onGlass() {
		let that = this
		// 绑定光标在显示盒子中的移动事件mousemove
		this.showBox.addEventListener('mousemove', function (e) {

			// console.log(that.bigPic);
			e = e || window.event
			let x = e.offsetX - that.mask.clientWidth / 2
			let y = e.offsetY - that.mask.clientHeight / 2

			//边界检查
			if (x < 0) {
				x = 20
			}
			if (x > that.showBox.clientWidth - that.mask.clientWidth) {
				x = that.showBox.clientWidth - that.mask.clientWidth
			}
			if (y < 0) {
				y = 0
			}
			if (y > that.showBox.clientHeight - that.mask.clientHeight) {
				y = that.showBox.clientHeight - that.mask.clientHeight
			}

			that.mask.style.left = x + 'px'
			that.mask.style.top = y + 'px'

			//右边大图反方向运行
			/*
			   背景图移距离X = 遮罩层移动距离x * 放大镜w/遮罩层w
			   背景图移距离y = 遮罩层移动距离y * 放大镜h/遮罩层h
			*/

			let moveX = (x * that.glassBox.clientWidth) / that.mask.clientWidth
			let moveY = (y * that.glassBox.clientHeight) / that.mask.clientHeight

			that.bigPic.style.left = `${-moveX}px`
			that.bigPic.style.top = `${-moveY}px`
		})
	}

	/**
	 * 移入显示遮罩层
	 * 移出隐藏遮罩层
	*/

	onShowHide() {
		let that = this
		this.showBox.addEventListener('mouseover', () => {
			this.mask.style.display = 'block'
			that.bigPic.style.display = 'block';
			this.init()
		})
		this.showBox.addEventListener('mouseout', () => {
			this.mask.style.display = 'none'
			that.bigPic.style.display = 'none';

		})

	}
	/*
		 背景图 = 放大镜 * 显示盒子 / 遮罩层
	 
	*/
	init() {
		let w = (this.glassBox.clientWidth * this.showBox.clientWidth) / this.mask.clientWidth
		let h = (this.glassBox.clientHeight * this.showBox.clientHeight) / this.mask.clientHeight
		this.bigPic.style.width = w + 'px'
		this.bigPic.style.height = h + 'px'
	}
	/*
		 选项切换
	*/
	onTab() {
		let that = this // 保存当前 glass放大镜对象到 that变量中
		for (let i = 0; i < this.uls.length; i++) {
			this.uls[i].addEventListener('click', function () {
				that.onClear()
				this.classList.add('active')

				//显示盒子图片和背景图片切换为相应图片
				// console.log('>>>'+this);
				let a = product.list[i]
				console.log('a:' + a);
				// that.showImg.src='${a}'
				// that.showImg.setAttribute('src', `${product.list[i]}`)
				that.showImg.setAttribute('src',`${a}`)
				that.bigPic.setAttribute('src', `${a}`)
				// console.log('a:'+ a);
			})
		}
	}



	/**
	 * 清除所有选项选中效果
	 */
	onClear() {
		for (let i = 0; i < this.uls.length; i++) {
			this.uls[i].classList.remove('active')
		}
	}
}


/*
  添加购物车
*/
function onAddCart() {
	// 1. 获取商品 product
	// 2. 获取购物车localStorage中原来商品数组,如果是第一次添加商品， 商品数组为[]
	let cartListStr = localStorage.getItem('DS-CART-LIST')
	let cartList = JSON.parse(cartListStr) || []

	//添加相同商品，改变数量
	//添加之前，根据id判断商品数组中是否已经存在，如果存在数量加一，否则添加新商品
	let oldProduct = cartList.find(item => item.id == product.id)
	if (oldProduct) {
		oldProduct.num++ //添加相同商品，改变数量
	} else {
		let cartProdcut = {
			id: product.id,
			name: product.product,
			price: product.price,
			url: product.picture,
			num: 1,
			state: false,
		}
		cartList.push(cartProdcut)
	}

	// 4. 持久化存储到购物车localStorage
	localStorage.setItem('DS-CART-LIST', JSON.stringify(cartList))
}

/*
 * 查看
 *  2. 跳转到购物车列表界面
 */
function onLookCart() {
	location.href = '../pages/shopcar.html'
}

loadProuctDetail()
